<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <script>
            let tree = {
                val: 1,
                children: [
                    { val: 2, children: [{ val: 5 }, { val: 6 }, { val: 7 }] },
                    { val: 3, children: [{ val: 8 }] },
                    { val: 4 },
                ],
            }
            //注意，这种方式必须在初始化的时候把根节点带上
            function treePath(root) {
                if (!root) return []
                const result = []
                function preOrder(root, path) {
                    //如果子节点不存在
                    let children = root.children || []
                    if (!children.length) {
                        return result.push([...path])
                    }
                    for (let i = 0; i < children.length; i++) {
                        path.push(children[i].val)
                        preOrder(children[i], path)
                        path.pop()
                    }
                }
                preOrder(root, [root.val])
                console.log(result)
            }
            treePath(tree)
        </script>
    </body>
</html>
